package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private IShopTypeService typeService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //查询redis缓存是否有
        List<String> list = stringRedisTemplate.opsForList().range(RedisConstants.SHOP_TYPE_KEY, 0, -1);
        if(!list.isEmpty()){
            //list.get(0) 其实是获取了整个List集合里的元素,0是第0个key
            List<ShopType> shopTypes = JSONUtil.toList(list.get(0), ShopType.class);
            return Result.ok(shopTypes);
        }
        //没有则查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        //把每一个的对象都转换为一组Json格式的字符串
        String jsonStr = JSONUtil.toJsonStr(typeList);
        //存储进redis
        stringRedisTemplate.opsForList().leftPushAll(RedisConstants.SHOP_TYPE_KEY,jsonStr);
        stringRedisTemplate.expire(RedisConstants.SHOP_TYPE_KEY,RedisConstants.SHOP_TYPE_TTL, TimeUnit.DAYS);
        return Result.ok(typeList);
    }
}
